<template>
  <div class="home-wrapper">
    <!-- 分割线 -->
    <div class="filters-wrapper"
         style="margin-bottom: 30px;">
      <div class="title total_title">项目数据
        <el-row class="fr"></el-row>
      </div>
      <el-row type="flex"
              align="middle"
              style="flex-wrap: wrap;"
              class="form-wrapper">
        <div>
          <span class="filter-label">账户名称：</span>
          <el-select :value="accountnames"
                     v-model="nameselect"
                     @change="selectAccount"
                     clearable="true"
                     placeholder="请选择"
                     size="small"
                     @visible-change="handleChange">
            <el-option v-for="item in accountArr"
                       :key="item.id_account"
                       :label="item.accountname"
                       :value="item.code" />
          </el-select>
        </div>
        <div style="margin-right: 10px;">
          <span class="filter-label">时间：</span>
          <el-date-picker v-model="data_wheres.time"
                          size="small"
                          type="daterange"
                          :picker-options="pickerOptions"
                          @change="dateChange"
                          range-separator="至"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期"
                          value-format="yyyy-MM-dd"
                          format="yyyy-MM-dd"
                          align="right"
                          :clearable="true" />
          <el-button type="primary"
                     @click="loadProject"
                     size="small"
                     style="width:80px;margin-left:20px"
                     icon="el-icon-search">查询
          </el-button>
        </div>
        <div class="chartsWrap">
          <el-button size="small"
                     type="primary"
                     @click="costDialogFormVisible = true">消耗分析</el-button>
          <el-button size="small"
                     type="primary"
                     @click="newDialogFormVisible = true">订单分析</el-button>
        </div>
        <el-dropdown :hide-on-click="false"
                     class="right">
          <el-button type="primary"
                     plain
                     icon="el-icon-s-operation"
                     class="zd"
                     style="display: flex; align-items: center; justify-content: center">选择显示列</el-button>
          <el-dropdown-menu slot="dropdown">
            <el-scrollbar style="height: 60vh"
                          width="200px">
              <el-checkbox-group v-model="check">
                <el-dropdown-item v-for="(item, index) in checkList"
                                  :key="index">
                  <el-checkbox :label="item"
                               :key="item"></el-checkbox>
                </el-dropdown-item>
              </el-checkbox-group>
            </el-scrollbar>
          </el-dropdown-menu>
        </el-dropdown>
      </el-row>
      <div class="draggable"
           style="padding: 20px">
        <el-table stripe
                  v-loading="loading"
                  :data="projectdatas?projectdatas.slice((currentPage-1)*pageSize,currentPage*pageSize):[]"
                  border
                  :header-cell-style="{'text-align':'center','background':'#f7f7f7','color':'#666'}"
                  style="width: 100%"
                  :default-sort="{prop: projectdatas.index, order: 'null'}"
                  @sort-change="sortData">
          <el-table-column prop="add_time"
                           label="添加时间"
                           align="center"
                           fixed>
          </el-table-column>
          <el-table-column prop="code"
                           label="账户id"
                           align="center"
                           fixed>
          </el-table-column>
          <el-table-column prop="account"
                           label="账户名称"
                           align="center"
                           fixed>
            <template slot-scope="scope">
              <router-link class="link"
                           :to="
              '/detail?code=' +
              `${scope.row.code}`
            ">{{scope.row.account}}</router-link>
            </template>
          </el-table-column>
          <el-table-column prop="type"
                           :formatter="statusFormatter"
                           label="投放平台"
                           align="center"
                           fixed>
          </el-table-column>
          <!--  <el-table-column prop="cost"
                           label="消耗"
                           align="center"
                           fixed>
          </el-table-column>
           <el-table-column prop="show"
                           label="显示次数"
                           align="center"
                           v-if="lists[0].ispass">
          </el-table-column>
          <el-table-column prop="convert"
                           label="转化次数"
                           align="center"
                           v-if="lists[1].ispass">
          </el-table-column>
          <el-table-column prop="click"
                           label="点击次数"
                           align="center"
                           v-if="lists[2].ispass">
          </el-table-column>

          <el-table-column prop="order_cnt"
                           label="总订单数量"
                           align="center"
                           v-if="lists[3].ispass">
          </el-table-column>
          <el-table-column prop="order_amount"
                           label="总订单总额"
                           align="center"
                           v-if="lists[4].ispass">
          </el-table-column>
          <el-table-column prop="payed_cnt"
                           label="支付订单数量"
                           align="center"
                           v-if="lists[5].ispass">
          </el-table-column>
          <el-table-column prop="payed_amount"
                           label="支付订单总额"
                           align="center"
                           v-if="lists[6].ispass">
          </el-table-column>
          <el-table-column prop="roi_order"
                           label="下单roi"
                           align="center"
                           v-if="lists[7].ispass">
          </el-table-column>
          <el-table-column prop="roi_succ"
                           label="成交roi"
                           align="center"
                           v-if="lists[8].ispass">
          </el-table-column>
          <el-table-column prop="ctr"
                           label="点击率"
                           align="center"
                           v-if="lists[9].ispass">
          </el-table-column>
          <el-table-column prop="convert_rate"
                           label="转化率"
                           align="center"
                           v-if="lists[10].ispass">
          </el-table-column>
          <el-table-column prop="convert_cost"
                           label="转化成本"
                           align="center"
                           v-if="lists[11].ispass">
          </el-table-column>
          <el-table-column prop="f_amount"
                           label="失败订单总额"
                           align="center"
                           v-if="lists[12].ispass">
          </el-table-column>
          <el-table-column prop="f_cnt"
                           label="失败订单数量"
                           align="center"
                           v-if="lists[13].ispass">
           </el-table-column> -->

          <el-table-column v-for="item in newCol"
                           :key="Math.random()"
                           :prop="item.prop"
                           :label="item.label"
                           align="center"
                           v-if="item.ispass">
          </el-table-column>
        </el-table>

        <div>
          <el-dialog title="消耗数据"
                     :modal-append-to-body="false"
                     :visible.sync="costDialogFormVisible"
                     @open="opened()"
                     append-to-body>
            <div id="costmain"
                 style="width: 900px; height: 500px; padding-top: 40px"></div>
          </el-dialog>
          <el-dialog title="订单数据"
                     :modal-append-to-body="false"
                     :visible.sync="newDialogFormVisible"
                     @open="open()"
                     append-to-body>
            <div id="main"
                 style="width: 900px; height: 500px; padding-top: 40px"></div>
          </el-dialog>
          <el-row type="flex"
                  justify="end"
                  style="margin-top: 20px">
            <el-pagination background
                           @current-change="handleCurrentChange"
                           :current-page="currentPage"
                           :page-size="pageSize"
                           layout=" prev, pager, next"
                           :total="total">
            </el-pagination>
          </el-row>
        </div>
</template>
<style>
</style>
<script>
import Sortable from 'sortablejs'
let echarts = require("echarts/lib/echarts");
require("echarts/lib/chart/line");
require("echarts/lib/component/tooltip");
require("echarts/lib/component/title");
require("echarts/lib/component/legend");
import { pageParams, dataTypes, parseTime } from "@/settings";
import draggable from "vuedraggable";
import { reqprojectdata, reqindexlist } from "@/api/request.js";
export default {

  data () {
    return {
      check: ['消耗', '总订单数量', '支付订单数量', '失败订单数量'],
      checkList: ['消耗', '总订单数量', '总订单总额', '支付订单数量', '支付订单总额', '显示次数', '转化次数', '点击次数',
        '下单roi', '成交roi', '点击率', '转化率', '转化成本', '失败订单总额', '失败订单数量'],
      col: [{
        label: '消耗',
        prop: 'cost',
        ispass: true
      }, {
        label: '总订单数量',
        prop: 'order_cnt',
        ispass: true
      }, {
        label: '总订单总额',
        prop: 'order_amount',
        ispass: false
      }, {
        label: '支付订单数量',
        prop: 'payed_cnt',
        ispass: true
      }, {
        label: '支付订单总额',
        prop: 'payed_amount',
        ispass: false
      }, {
        label: '显示次数',
        prop: 'show',
        ispass: false
      }, {
        label: '转化次数',
        prop: 'convert',
        ispass: false
      }, {
        label: '点击次数',
        prop: 'click',
        ispass: false
      }, {
        label: '下单roi',
        prop: 'roi_order',
        ispass: false
      }, {
        label: '成交roi',
        prop: 'roi_succ',
        ispass: false
      }, {
        label: '点击率',
        prop: 'ctr',
        ispass: false
      }, {
        label: '转化率',
        prop: 'convert_rate',
        ispass: false
      }, {
        label: '转化成本',
        prop: 'convert_cost',
        ispass: false
      }, {
        label: '失败订单总额',
        prop: 'f_amount',
        ispass: false
      }, {
        label: '失败订单数量',
        prop: 'f_cnt',
        ispass: false
      }],
      dropCol: [{
        label: '消耗',
        prop: 'cost',
      }, {
        label: '总订单数量',
        prop: 'order_cnt',
      }, {
        label: '总订单总额',
        prop: 'order_amount',
      }, {
        label: '支付订单数量',
        prop: 'payed_cnt',
      }, {
        label: '支付订单总额',
        prop: 'payed_amount',
      }, {
        label: '显示次数',
        prop: 'show',
      }, {
        label: '转化次数',
        prop: 'convert',
      }, {
        label: '点击次数',
        prop: 'click',
      }, {
        label: '下单roi',
        prop: 'roi_order',
      }, {
        label: '成交roi',
        prop: 'roi_succ',
      }, {
        label: '点击率',
        prop: 'ctr',
      }, {
        label: '转化率',
        prop: 'convert_rate',
      }, {
        label: '转化成本',
        prop: 'convert_cost',
      }, {
        label: '失败订单总额',
        prop: 'f_amount',
      }, {
        label: '失败订单数量',
        prop: 'f_cnt',
      }],
      costDialogFormVisible: false,
      newDialogFormVisible: false,
      projectchecked: [], // 选项画面使用
      accountnames: "",
      selectid: "",
      nameselect: "",
      account_id: "",
      loading: false,
      accountArr: [],
      chartsCost: [],
      chartsAccount: [],
      chartsOrder_cnt: [],
      chanrtsPayed_cnt: [],
      chartsF_cnt: [],
      projectdataschecked: [], // 数据真实使用
      // jd_search: '',
      pageSize: 10,
      newCol: [{
        label: '消耗',
        prop: 'cost',
        ispass: true
      }, {
        label: '总订单数量',
        prop: 'order_cnt',
        ispass: true
      }, {
        label: '支付订单数量',
        prop: 'payed_cnt',
        ispass: true
      }, {
        label: '失败订单数量',
        prop: 'f_cnt',
        ispass: true
      }],
      currentPage: 1,
      total: "",
      activeName: "first",
      loading_realtime: false,
      loading_chart: false,
      loading_data: false,
      centerDialogVisible: false,
      tasktime: parseTime(new Date(), "{y}-{m}-{d}"),
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick (picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick (picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick (picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      value1: [new Date(2000, 10, 10, 10, 10), new Date(2000, 10, 11, 10, 10)],
      params: {
        startTime: "",
        endTime: "",
        date: "",
      },
      customTable: false,
      realdata: {
        cost: 0,
        convert: 0,
        convert_cost: 0,
        clue_total: 0,
        clue_cost: 0,
      },
      datatype: [],
      filter: {
        projects: [],
        accounts: [],
        managers: [],
        optimizers: [],
        departments: [],
      },
      projects: [],
      accounts: [],
      accounts_all: [], //因为这个数据只显示前20条，过滤时要按全部数据过滤
      managers: [],
      optimizers: [],
      departments: [],
      real_wheres: {
        projectid: "",
        accountid: "",
        managerid: "",
        optimizerid: "",
        departmentid: "",
      },
      chart_wheres: [
        {
          projectid: "",
          accountid: "",
          datatype: "cost",
          time: [
            parseTime(new Date(), "{y}-{m}-{d} 00:00:00"),
            parseTime(new Date()),
          ],
        },
      ],
      data_wheres: {
        projectid: "",
        accountid: "",
        // datatype: 'cost',
        order: "desc",
        order_field: "cost",
        time: [
          parseTime(new Date(), "{y}-{m}-{d} 00:00:00"),
          parseTime(new Date()),
        ],

        page: 1,
        number: pageParams.pageSize,
        accounts: [],
        projects: [],
      },
      // project: {
      //     projectid: '',
      //     accountid: '',
      //     datatype: '',
      //     time: [ parseTime(new Date()), parseTime(new Date())],
      //     accounts: [],
      //     projects: []
      // },
      projectdatas: [],
      projectlist: [],
      dingdanlist: [],
      projectdatatotal: 0,
      tasks: [],
      task: null,
      isSelectAllColumn: false,
    };
  },
  // created() {
  //     let tm = parseTime(new Date())
  //     console.log('tm', tm)
  //     this.chart_wheres.time = [tm, tm]
  //     this.project.time = [tm, tm]
  // },
  mounted () {
    this.loading = true;
    // this.datatype = dataTypes;
    // this.selectAllColumn(true);
    // // console.log('index_column', this.$store.state.user.index_column)
    // let cols = this.$store.state.user.index_column;
    // if (cols && cols.length > 0) {
    //   this.projectdataschecked = cols;
    // } else {
    //   this.projectdataschecked = this.projectchecked.slice();
    // }
    // this.loadData();
    //项目数据
    this.shuju();
    this.columnDrop()
  },
  computed: {
    taskbox: {
      get () {
        return this.task != null;
      },
      set (v) {
        if (!v) {
          this.task = null;
        }
      },
    },
  },
  watch: {
    projectdatas: {
      immediate: true,
      handler (newVal, oldVal) {
        //消耗
        if (newVal) {
          this.chartsAccount = []
          this.chartsCost = []
          this.chartsOrder_cnt = []
          this.chanrtsPayed_cnt = []
          this.chartsF_cnt = []
          this.projectdatas.forEach(item => {
            this.chartsCost.push(item.cost)
          })
          this.projectdatas.forEach(item => {
            this.chartsAccount.push(item.account)
          })
          this.projectdatas.forEach(item => {
            this.chartsOrder_cnt.push(item.order_cnt)
          })
          this.projectdatas.forEach(item => {
            this.chanrtsPayed_cnt.push(item.payed_cnt)
          })
          this.projectdatas.forEach(item => {
            this.chartsF_cnt.push(item.f_cnt)
          })
        }

      },
    },
    check (newVal) {
      if (newVal) {
        this.newCol = [];
        var arr = this.checkList.filter(i => newVal.indexOf(i) < 0) //未选中
        this.col.map(i => {
          if (arr.indexOf(i.label) !== -1) {
            i.ispass = false
          } else {
            i.ispass = true
            if (i.ispass == true) {
              this.newCol.push(i)
            }
          }
        })
        const newtr = document.querySelector(".el-table__header-wrapper tr");
        this.sortable = Sortable.create(newtr, {
          animation: 180,
          delay: 0,
          onEnd: (evt) => {
            if (evt.newIndex > 3) {
              var newlist = this.newCol
              const oldItem = this.newCol[evt.oldIndex - 4];
              this.newCol.splice(evt.oldIndex - 4, 1);
              this.newCol.splice(evt.newIndex - 4, 0, oldItem);
            }
          },
        });
      }

    },
  },
  methods: {
    columnDrop () {
      const wrapperTr = document.querySelector(".el-table__header-wrapper tr");
      this.sortable = Sortable.create(wrapperTr, {
        animation: 180,
        delay: 0,
        onEnd: (evt) => {
          if (evt.newIndex > 3) {
            const oldItem = this.newCol[evt.oldIndex - 4];
            this.newCol.splice(evt.oldIndex - 4, 1);
            this.newCol.splice(evt.newIndex - 4, 0, oldItem);
          }
        },
      });
    },
    drawChart () {
      // 基于准备好的dom，初始化echarts实例
      let myChart = this.$echarts.init(document.getElementById("main"));
      // 指定图表的配置项和数据
      let option = {
        title: {
          text: "广告订单表",
        },
        color: ['#5470c6', '#91cc75', '#fac858'],
        tooltip: {},
        legend: {
          data: ["总订单数量", "支付订单数量", "失败订单数量"],
        },
        xAxis: {
          data: this.chartsAccount,
        },
        yAxis: {},
        dataZoom: [
          {
            type: 'slider',
            show: true,
            start: 0,
            end: 10,
            handleSize: 8
          },
          {
            type: 'inside',
            start: 0,
            end: 10
          },
          {
            type: 'slider',
            show: true,
            yAxisIndex: 0,
            filterMode: 'empty',
            width: 12,
            height: '70%',
            handleSize: 8,
            showDataShadow: false,
            left: '93%'
          }
        ],
        series: [
          {
            name: "总订单数量",
            type: "bar",
            data: this.chartsOrder_cnt,
          },
          {
            name: "支付订单数量",
            type: "bar",
            data: this.chanrtsPayed_cnt,
          },
          {
            name: "失败订单数量",
            type: "bar",
            data: this.chartsF_cnt,
          },
        ],
      };
      myChart.clear();
      // 使用刚指定的配置项和数据显示图表。
      myChart.setOption(option);
    },
    costdrawChart () {
      // 基于准备好的dom，初始化echarts实例
      let myChart = this.$echarts.init(document.getElementById("costmain"));
      // 指定图表的配置项和数据
      let option = {
        title: {
          text: "广告消耗表",
        },
        color: ['#fc8452'],
        tooltip: {},
        legend: {
          data: ["消耗"],
        },
        xAxis: {
          data: this.chartsAccount,
        },
        yAxis: {},
        dataZoom: [
          {
            type: 'slider',
            show: true,
            start: 0,
            end: 50,
            handleSize: 8
          },
          {
            type: 'inside',
            start: 0,
            end: 50
          },
          {
            type: 'slider',
            show: true,
            yAxisIndex: 0,
            filterMode: 'empty',
            width: 12,
            height: '70%',
            handleSize: 8,
            showDataShadow: false,
            left: '93%'
          }
        ],
        series: [
          {
            name: "消耗",
            type: "bar",
            data: this.chartsCost,
          },
        ],
      };
      myChart.clear();
      // 使用刚指定的配置项和数据显示图表。
      myChart.setOption(option);
    },
    opened () {
      this.$nextTick(() => {
        this.costdrawChart();
      });
    },
    open (val) {
      this.$nextTick(() => {
        this.drawChart();
      });
    },
    handleCurrentChange (val) {
      this.currentPage = val;
    },
    shuju () {
      reqprojectdata().then((res) => {
        if (res.code === 1) {
          this.loading = false;
          const { data } = res.data;
          this.projectdatas = data;
          this.total = this.projectdatas.length;
          data.forEach((item) => {
            item.accountname = item.account;
          });
          this.accountArr = data;
        }
      }).catch(() => {

      })
    },

    //项目名称下拉框
    selectAccount (e) {
      this.loading = true;
      this.selectid = e;
      if (this.selectid) {
        if (this.params.startTime && this.params.endTime) {
          reqprojectdata({
            account_id: this.selectid,
            stat_time: this.params.startTime,
            end_time: this.params.endTime,
          }).then((res) => {
            if (res.code === 1) {
              this.loading = false;
              const { data } = res.data;
              this.projectdatas = data;
              this.total = this.projectdatas.length;
            } else {
              this.projectdatas = [];
            }
          });
        } else {
          reqprojectdata({ account_id: this.selectid }).then((res) => {
            if (res.code === 1) {
              this.loading = false;
              const { data } = res.data;
              this.projectdatas = data;
              this.total = this.projectdatas.length;
            } else {
              this.projectdatas = [];
            }
          });
        }
      } else {
        reqprojectdata().then((res) => {
          if (res.code === 1) {
            this.loading = false;
            const { data } = res.data;
            this.projectdatas = data;
            this.total = this.projectdatas.length;
          } else {
            this.projectdatas = [];
          }
        });
      }
    },
    //时间选择器
    dateChange (picker) {
      if (picker) {
        this.params.startTime = picker[0];
        this.params.endTime = picker[1];
      }
      if (this.selectid) {
        this.loading = true;
        reqprojectdata({
          account_id: this.selectid,
          stat_time: this.params.startTime,
          end_time: this.params.endTime,
        }).then((res) => {
          if (res.code === 1) {
            this.loading = false;
            const { data } = res.data;
            this.projectdatas = data;
            this.total = this.projectdatas.length;
          } else {
            this.loading = false;
            this.projectdatas = [];
          }
        });
      } else {
        this.loading = true;
        reqprojectdata({
          stat_time: this.params.startTime,
          end_time: this.params.endTime,
        }).then((res) => {
          if (res.code === 1) {
            this.loading = false;
            const { data } = res.data;
            this.projectdatas = data;
            this.total = this.projectdatas.length;
          } else {
            this.loading = false;
            this.projectdatas = [];
          }
        });
      }
    },
    //查询
    loadProject () {
      this.loading = true;
      if (this.selectid) {
        reqprojectdata({
          account_id: this.selectid,
          stat_time: this.params.startTime,
          end_time: this.params.endTime,
        }).then((res) => {
          if (res.code === 1) {
            this.loading = false;
            const { data } = res.data;
            this.projectdatas = data;
            this.total = this.projectdatas.length;
          } else {
            this.loading = false;
            this.projectdatas = [];
          }
        });
      } else {
        reqprojectdata({
          stat_time: this.params.startTime,
          end_time: this.params.endTime,
        }).then((res) => {
          if (res.code === 1) {
            this.loading = false;
            const { data } = res.data;
            this.projectdatas = data;
            this.total = this.projectdatas.length;
          } else {
            this.loading = false;
            this.projectdatas = [];
          }
        });
      }
    },
    statusFormatter (row, column) {
      const type = row.type_id;
      if (type == 1) {
        return "京东";
      } else if (type == 2) {
        return "淘宝";
      } else if (type == 3) {
        return "拼多多";
      }
    },
    //刷新
    // openList(id) {
    //   this.account_id = id;
    //   this.loading = true;
    //   if (this.params.startTime && this.params.endTime) {
    //     reqindexlist({
    //       account_id: this.account_id,
    //       stat_time: this.params.startTime,
    //       end_time: this.params.endTime,
    //     }).then((res) => {
    //         if (res.code == 1) {
    //           location.reload();
    //           this.loading = false;
    //         }
    //     });
    //   } else {
    //     reqindexlist({ account_id: this.account_id,}).then((res) => {
    //       if (res.code == 1) {
    //         location.reload();
    //         this.loading = false;
    //       }
    //     });
    //   }
    // },
    loadData () {
      this.$axios.get("/report/filter").then((e) => {
        let data = e.data;
        this.filter = data;
        this.projects = this.filter.projects.slice(0);
        this.managers = this.filter.managers.slice(0);
        this.optimizers = this.filter.optimizers.slice(0);
        this.departments = this.filter.departments.slice(0);
        this.accounts_all = this.filter.accounts.slice(0);
        if (this.filter.accounts.length > 20) {
          this.accounts = this.filter.accounts.slice(0, 20);
        } else {
          this.accounts = this.filter.accounts.slice(0);
        }
        this.accounts.splice(0, 0, {
          id: "",
          title: "全部",
          optimizers: [],
        });

        this.projects.splice(0, 0, {
          id: "",
          title: "全部",
          optimizers: [],
        });
        this.managers.splice(0, 0, {
          id: "",
          title: "全部",
        });
        this.optimizers.splice(0, 0, {
          id: "",
          title: "全部",
        });
        this.departments.splice(0, 0, {
          id: "",
          title: "全部",
        });
        this.initChartWhere(this.chart_wheres[0]);
        this.initChartWhere(this.data_wheres);
        // console.log('this.filter', this.filter)
      });
      this.loadRealTimeData();
      this.loadChartData({});
      this.loadProjectData({});
      this.loadTaskData({});
    },
    handleClick (tab, event) {
      console.log(tab, event);
    },
    queryWarehouseHandle (e) {
      console.log(e);
    },
    loadRealTimeData () {
      this.loading_realtime = true;
      // let param = {
      //     projectid: this.projectid,
      //     accountid: this.accountid,
      //     managerid: this.managerid,
      //     optimizerid: this.optimizerid,
      //     departmentid: this.departmentid
      // }
      this.$axios.get("/project/realdata", this.real_wheres).then((e) => {
        this.loading_realtime = false;
        this.realdata = e.data;
      });
    },
    loadChartData () {
      var param = [];
      this.chart_wheres.forEach((ele) => {
        let p = {
          projectid: ele.projectid,
          accountid: ele.accountid,
          datatype: ele.datatype,
          time: ele.time,
        };
        param.push(p);
      });
      this.loading_chart = true;
      this.$axios
        .get("/project/chart", { type: "index", data: param })
        .then((e) => {
          this.loading_chart = false;
          if (JSON.stringify(e.data) != "[]") {
            // if(e.data.series.length > 1){
            //     e.data.series.forEach(function(item, index){
            //         e.data.xAxis[index].axisPointer.label = {
            //             formatter: function (params) {
            //                 return params.value + (params.seriesData.length ? ' : ' + params.seriesData[0].data : '');
            //             }
            //         }
            //     })
            // }
            // console.info(e.data);
            this.drawLine(e.data);
          }
        });
    },
    loadProjectData (param) {
      this.loading_data = true;
      let tmp = JSON.parse(JSON.stringify(this.data_wheres));
      delete tmp["accounts"];
      delete tmp["projects"];
      for (const k in param) {
        tmp[k] = param[k];
      }
      if (!tmp["page"]) {
        tmp["page"] = 1;
      }
      this.curPage = tmp["page"];
      //console.log('tmp', tmp)

      // this.$axios.get('/project/data', tmp)
      //     .then(e => {
      //         this.loading_data = false
      //         this.projectdatas = e.data.items
      //         this.projectdatatotal = e.data.total
      //         // console.log(e.data.items)
      //     })
      this.$axios.get("/project/data", tmp).then((e) => {
        this.loading_data = false;
        this.projectlist = e.data.items;
        this.projectdatatotal = e.data.total;
        // console.log(e.data.items)
      });

      this.$axios.get("/project/data", tmp).then((e) => {
        this.loading_data = false;
        this.projectdatas = e.data.items;
        this.projectdatatotal = e.data.total;
        // console.log(e.data.items)
      });
      // this.$axios.get('/project/data', tmp)
      //     .then(e => {
      //         this.loading_data = false
      //         this.projectlist = e.data.items
      //         this.projectdatatotal = e.data.total
      //         // console.log(e.data.items)
      //     })
    },
    loadTaskData (param) {
      param["own"] = 1;
      param["time"] = this.tasktime;
      this.$axios.get("/task/list", param).then((e) => {
        let data = e.data.items;
        data.forEach((ele) => {
          ele.unfoldshow = false;
        });
        this.tasks = data;
      });
    },
    initChartWhere (item) {
      // item['projects'] = this.filter.projects.slice(0)
      this.$set(item, "projects", this.filter.projects.slice(0));
      if (this.filter.accounts.length > 20) {
        // item['accounts'] = this.filter.accounts.slice(0, 20)
        this.$set(item, "accounts", this.filter.accounts.slice(0, 20));
      } else {
        // item['accounts'] = this.filter.accounts.slice(0)
        this.$set(item, "accounts", this.filter.accounts.slice(0));
      }
      item.projects.splice(0, 0, {
        id: "",
        title: "全部",
        optimizers: [],
      });
      item.accounts.splice(0, 0, {
        id: "",
        title: "全部",
        optimizers: [],
      });
    },
    addWhereClick () {
      if (this.chart_wheres.length >= 3) {
        this.$message("已经添加到最多了");
        return;
      }
      this.chart_wheres.push({
        projectid: "",
        accountid: "",
        datatype: "cost",
        // time: [ new Date((new Date()).getTime() - 3600 * 24 * 1000), new Date()],
        time: [
          parseTime(new Date(), "{y}-{m}-{d} 00:00:00"),
          parseTime(new Date()),
        ],
      });
      this.initChartWhere(this.chart_wheres[this.chart_wheres.length - 1]);
    },
    delWhereClick (idx) {
      this.chart_wheres.splice(idx, 1);
    },
    chartSearchClick () {
      // console.log('chartSearchClick', param)
      // 服务器查询图表数据
      this.loadChartData({});
    },
    projectDataSearchClick () {
      let tmp = JSON.parse(JSON.stringify(this.data_wheres));
      delete tmp["accounts"];
      delete tmp["projects"];
      // console.log('projectDataSearchClick', param)
      // if (param['export']) {
      location.href =
        "http://ad.adjdds.com/api/export/project/?json=" + JSON.stringify(tmp);
      // window.open('http://ad.adjdds.com/api/export/project/?json=' + JSON.stringify(tmp), '_blank')
      // this.$router.push()
      // return
      // }
      // 服务器查询函数
      // this.loadProjectData(param)
    },
    filterAccount (type, e) {
      console.log(type, e);
      let acts = this.accounts_all.filter((ele) => {
        return ele.title.indexOf(e) != -1;
      });
      if (type === "") {
        this.accounts = acts;
      } else if (type == "data_wheres") {
        this.data_wheres.accounts = acts;
      } else {
        this.chart_wheres[type].accounts = acts;
      }
    },
    selectChangeChart (item, ele) {
      var pjs = this.filter.projects.slice(0);
      var acts = this.filter.accounts.slice(0);
      if ("projects" == ele) {
        // 清除掉选中项
        item["accountid"] = "";
      }
      if (item["projectid"] != "") {
        pjs = pjs.filter((ele) => {
          return ele.id == item["projectid"];
        });
        acts = acts.filter((ele) => {
          var result = pjs.findIndex((item) => {
            return item["id"] == ele["pid"];
          });
          return result != -1;
        });
      }

      if (acts.length > 20) {
        acts = acts.slice(0, 20);
      }
      acts.splice(0, 0, {
        id: "",
        title: "全部",
        optimizers: [],
      });
      this.accounts = acts;
      item["accounts"] = acts;
    },
    selectChange (t, ele, id) {
      console.log("selectChange", ele, id); //, 'projectid', this.projectid, 'accountid', this.accountid)
      // 计算各项内容
      var pjs = this.filter.projects.slice(0);
      var mgrs = this.filter.managers.slice(0);
      var acts = this.filter.accounts.slice(0);
      var opts = this.filter.optimizers.slice(0);
      var deps = this.filter.departments.slice(0);
      switch (ele) {
        case "departments":
          this.real_wheres.projectid = "";
        // break omitted
        // eslint-disable-next-line no-fallthrough
        case "projects":
          this.real_wheres.accountid = "";
        // eslint-disable-next-line no-fallthrough
        case "accounts":
          this.real_wheres.managerid = "";
          this.real_wheres.optimizerid = "";
        // break omitted
        // eslint-disable-next-line no-fallthrough
        default:
          break;
      }
      if (this.real_wheres.projectid != "") {
        pjs = pjs.filter((ele) => {
          return ele.id == this.real_wheres.projectid;
        });
        mgrs = mgrs.filter((ele) => {
          var result = pjs.findIndex((item) => {
            return item["managerid"] == ele.id;
          });
          return result != -1;
        });
        acts = acts.filter((ele) => {
          var result = pjs.findIndex((item) => {
            return item["id"] == ele["pid"];
          });
          return result != -1;
        });
        opts = opts.filter((ele) => {
          var result = acts.findIndex((item) => {
            return item["optimizerid"] == ele.id;
          });
          return result != -1;
        });
        deps = deps.filter((ele) => {
          var result = pjs.findIndex((item) => {
            return item["departmentid"] == ele["id"];
          });
          return result != -1;
        });
      }
      if (this.real_wheres.accountid != "") {
        acts = acts.filter((ele) => {
          return ele.id == this.real_wheres.accountid;
        });
        pjs = pjs.filter((ele) => {
          var result = acts.findIndex((item) => {
            return item["pid"] == ele.id;
          });
          return result != -1;
        });
        mgrs = mgrs.filter((ele) => {
          var result = pjs.findIndex((item) => {
            return item["managerid"] == ele.id;
          });
          return result != -1;
        });

        opts = opts.filter((ele) => {
          var result = acts.findIndex((item) => {
            return item["optimizerid"] == ele.id;
          });
          return result != -1;
        });
        deps = deps.filter((ele) => {
          var result = pjs.findIndex((item) => {
            return item["departmentid"] == ele["id"];
          });
          return result != -1;
        });
      }
      if (this.real_wheres.managerid != "") {
        console.log("this.managerid", this.real_wheres.managerid);
        pjs = pjs.filter((ele) => {
          return ele.managerid == this.real_wheres.managerid;
        });
        mgrs = mgrs.filter((ele) => {
          var result = pjs.findIndex((item) => {
            return item["managerid"] == ele.id;
          });
          return result != -1;
        });
        acts = acts.filter((ele) => {
          var result = pjs.findIndex((item) => {
            return item["id"] == ele["pid"];
          });
          return result != -1;
        });
        opts = opts.filter((ele) => {
          var result = acts.findIndex((item) => {
            return item["optimizerid"] == ele.id;
          });
          return result != -1;
        });
        deps = deps.filter((ele) => {
          var result = pjs.findIndex((item) => {
            return item["departmentid"] == ele["id"];
          });
          return result != -1;
        });
      }
      if (this.real_wheres.departmentid != "") {
        pjs = pjs.filter((ele) => {
          return ele.departmentid == this.real_wheres.departmentid;
        });
        mgrs = mgrs.filter((ele) => {
          var result = pjs.findIndex((item) => {
            return item["managerid"] == ele.id;
          });
          return result != -1;
        });
        acts = acts.filter((ele) => {
          var result = pjs.findIndex((item) => {
            return item["id"] == ele["pid"];
          });
          return result != -1;
        });
        opts = opts.filter((ele) => {
          var result = acts.findIndex((item) => {
            return item["optimizerid"] == ele.id;
          });
          return result != -1;
        });
        deps = deps.filter((ele) => {
          var result = pjs.findIndex((item) => {
            return item["departmentid"] == ele["id"];
          });
          return result != -1;
        });
      }
      if (this.real_wheres.optimizerid != "") {
        // 查询本优化师的所有项目
        opts = opts.filter((ele) => {
          return ele.id == this.real_wheres.optimizerid;
        });
        acts = acts.filter((ele) => {
          return this.real_wheres.optimizerid == ele["optimizerid"];
        });
        pjs = pjs.filter((ele) => {
          var result = acts.findIndex((item) => {
            return item.pid == ele.id;
          });
          return result != -1;
        });
        mgrs = mgrs.filter((ele) => {
          var result = pjs.findIndex((item) => {
            return item["managerid"] == ele.id;
          });
          return result != -1;
        });
        deps = deps.filter((ele) => {
          var result = pjs.findIndex((item) => {
            return item["departmentid"] == ele["id"];
          });
          return result != -1;
        });
      }
      if (this.real_wheres.departmentid != "") {
        deps = deps.filter((ele) => {
          return ele.id == this.real_wheres.departmentid;
        });
        pjs = pjs.filter((ele) => {
          var result = deps.findIndex((item) => {
            return item.id == ele.departmentid;
          });
          return result != -1;
        });
        acts = acts.filter((ele) => {
          var result = pjs.findIndex((item) => {
            return item["id"] == ele["pid"];
          });
          return result != -1;
        });
        opts = opts.filter((ele) => {
          var result = acts.findIndex((item) => {
            return item["optimizerid"] == ele.id;
          });
          return result != -1;
        });
      }
      if (this.real_wheres.departmentid != "" && ele != "projects") {
        pjs.splice(0, 0, {
          id: "",
          title: "全部",
          optimizers: [],
        });
        this.projects = pjs;
        // if (pjs.length == 2) {
        //     this.projectid = pjs[1].id
        // }
      } else {
        pjs = this.filter.projects.slice(0);
        pjs.splice(0, 0, {
          id: "",
          title: "全部",
          optimizers: [],
        });
        this.projects = pjs;
      }
      if (ele != "accounts") {
        this.accounts_all = acts;
        if (acts.length > 20) {
          acts = acts.slice(0, 20);
        }
        acts.splice(0, 0, {
          id: "",
          title: "全部",
          optimizers: [],
        });
        this.accounts = acts;
        // if (acts.length == 2) {
        //     this.accountid = acts[1].id
        // }
      }
      if (ele != "managers") {
        // manager
        mgrs.splice(0, 0, {
          id: "",
          title: "全部",
          optimizers: [],
        });
        this.managers = mgrs;
        // if (mgrs.length == 2) {
        //     this.managerid = mgrs[1].id
        // }
      }
      if (ele != "optimizers") {
        opts.splice(0, 0, {
          id: "",
          title: "全部",
          optimizers: [],
        });
        this.optimizers = opts;
        // if (opts.length == 2) {
        //     this.optimizerid = opts[1].id
        // }
      }
      if (ele != "departments") {
        // deps.splice(0, 0, {
        //     id: '',
        //     title: '全部',
        //     optimizers: []
        // })
        // this.departments = deps
        // if (deps.length == 2) {
        //     this.departmentid = deps[1].id
        // }
      }
    },
    drawLine (options) {
      let myChart = echarts.init(document.getElementById("myChart"));
      let sizeFun = function () {
        myChart.resize();
      };
      window.addEventListener("resize", sizeFun);
      // options = JSON.parse(' {"code":1,"msg":"\u8bf7\u6c42\u6210\u529f","data":{"xAxis":{"type":"category","data":["Mon","Tue","Wed","Thu","Fri","Sat","Sun"]},"legend":{"data":["邮件营销","联盟广告","视频广告","直接访问","搜索引擎"]},"yAxis":{"type":"value"},"series":[{"data":[820,932,901,934,1290,1330,1320],"type":"line","name":"邮件营销"}]}}')
      // options = options.data
      // 绘制图表
      myChart.setOption(options, true);
    },
    getMissions (task) {
      // console.log(task)
      let ret = task.missions;
      if (!task.unfoldshow && ret.length > 3) {
        ret = task.missions.slice(0, 3);
      }
      return ret;
    },
    openMsg (item) {
      // console.log(item)
      this.task = item;
      // if (item.tast_progress == '已完成') {
      //     this.$alert(item.tast_name, '任务内容', {
      //         confirmButtonText: '确定'
      //     })
      //     return
      // }
      // this.$confirm(item.tast_name, '任务内容', {
      //     confirmButtonText: '确认完成',
      //     cancelButtonText: '取消',
      //     type: 'info'
      // }).then(() => {
      //     // 发送已读请求
      //     this.$axios.post('/task/finish', {
      //         id: item.id
      //     }).then(() => {
      //         item.tast_progress = '已完成'
      //     })
      // })
    },
    changeTaskStatus (status) {
      // 发送已读请求
      this.$axios
        .post("/task/finish", {
          id: this.task.id,
          status: status,
        })
        .then((e) => {
          // console.log('====', e) // e.data.new_status
          // this.tasks.forEach(ele => {
          //     ele.missions.forEach(t => {
          //         if (t.id == this.task.id) {
          //             t.tast_progress = e.new_status
          //         }
          //     })
          // })
          this.task.status = status;
          this.task.tast_progress = e.data.new_status; // '已完成'
          this.task = null;
        });
    },
    // rowDrop(){
    //     var el = document.getElementById('items');
    //     var sortable = Sortable.create(el);
    // }
    unfold (index) {
      this.tasks[index].unfoldshow = !this.tasks[index].unfoldshow;
    },
    sortData (data) {
      this.data_wheres.order_field = data.prop;
      this.data_wheres.order = data.order == "ascending" ? "asc" : "desc";
      this.loadProjectData({});
    },
    openColumn () {
      this.customTable = true;
      this.projectchecked = this.projectdataschecked.slice();
      console.log(this.projectchecked);
    },
    removeColumn (id) {
      let idx = this.projectchecked.findIndex((e) => e == id);
      if (idx > -1) {
        this.projectchecked.splice(idx, 1);
      }
    },
    getColumnName (id) {
      let item = this.prolists.find((ele) => {
        return ele.id == id;
      });
      if (item) {
        return item.name;
      } else {
        return "未知";
      }
    },
    applyColumn () {
      if (this.projectchecked.length <= 0) {
        this.$message.error("没有选中任何项目");
        return;
      }
      this.projectdataschecked = [];
      // console.log('this.projectdataschecked', this.projectchecked)
      // 增加网络请求保存
      this.loading_data = true;
      this.$axios
        .post("/user/edit", {
          index_column: this.projectchecked,
        })
        .then(() => {
          // console.log('/user/edit result', e)
          this.loading_data = false;
          this.customTable = false;
          this.$nextTick(() => {
            this.projectdataschecked = this.projectchecked.slice();
          });
          // 修改store中的数据
          this.$store.commit(
            "user/SET_INDEX_COLUMN",
            this.projectchecked.slice(0)
          );
          // this.$store.dispatch("user/SET_INDEX_COLUMN", this.projectchecked.slice(0))
        })
        .catch(() => {
          this.loading_data = false;
          this.customTable = false;
        });

      // this.$forceUpdate()
    },
    getColumnProp (id) {
      let item = this.prolists.find((ele) => {
        return ele.id == id;
      });
      if (item) {
        return item.prop;
      } else {
        return "未知";
      }
    },
    getSortable (id) {
      let item = this.prolists.find((ele) => {
        return ele.id == id;
      });
      if (item) {
        return item.sortable;
      } else {
        return false;
      }
    },
    selectAllColumn (event) {
      // console.log('event', event)
      if (event) {
        this.prolists.forEach((ele) => {
          if (this.projectchecked.findIndex((e) => e.id == ele.id) == -1) {
            this.projectchecked.push(ele.id);
          }
        });
        this.isSelectAllColumn = true;
      } else {
        this.projectchecked = [];
      }
    },
    isIndeterminate () {
      if (
        this.projectchecked.length > 0 &&
        this.projectchecked.length < this.prolists.length
      ) {
        return true;
      }
      return false;
    },
  },
};
</script>
<style>
.link:hover {
  color: rgb(64, 162, 255);
}
.home-wrapper {
  position: relative;
}
.el-dialog {
  width: 920px;
}
.form-wrapper {
  padding-right: 30px;
}
.form-wrapper {
  justify-content: space-between;
}
</style>
